package com.woniu.woniuproject.Job;

import com.woniu.woniuproject.config.SendSms;
import com.woniu.woniuproject.entity.*;
import com.woniu.woniuproject.exceptions.IlltionExption;
import com.woniu.woniuproject.exceptions.PhoneExption;
import com.woniu.woniuproject.exceptions.UpmysqlException;
import com.woniu.woniuproject.mapper.*;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 功能描述:<br>
 * 〈〉
 *
 * @author EDZ
 * @create 2020/11/16
 * @since 1.0.0
 */

public class Thread extends QuartzJobBean {

    @Autowired
    Debt_infoMapper debt_infoMapper;
    @Autowired
    LooseLabelMapper looseLabelMapper;
    @Autowired
    moneyCountMapper moneyCountMapper;
    @Autowired
    Account_logMapper account_logMapper;
    @Autowired
    AccountMapper accountMapper;
    @Autowired
    SendSms sendSms;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    Product_accountMapper product_accountMapper;
    @Autowired
    looselabel_recordMapper looselabel_recordMappers;
    Logger logger = LoggerFactory.getLogger(Thread.class);

    @Override
    @Transactional
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        //更新贷款人权重
        List<Debt_info> list = debt_infoMapper.selectall();
        Date nowdate = new Date();
        for (int i=0;i<list.size();i++){
            Date date = list.get(i).getLoanstartdate();//贷款日期
          if(nowdate.getMonth()==date.getMonth()){
              if(nowdate.getDate()-date.getDate()>0){
                  int connection=list.get(i).getConnection()+1;
                  int id = list.get(i).getId();
                  if(debt_infoMapper.updateconnection(connection,id)>0){
                      logger.info("今日已更新贷款债权");
                  }else {
                      logger.info("贷款人权重更新失败");
                  }
              }
          }
        }



        //更新待发布权重
        List<LooseLabel>  LooseLabellist=looseLabelMapper.selectByAplays(null,null);
        System.out.println(LooseLabellist+"=======");
        for (int i=0;i<LooseLabellist.size();i++){
            Date date = LooseLabellist.get(i).getDebordate();//申请日期
            System.out.println(date+"=========");
            if(nowdate.getMonth()==date.getMonth()){
                if(nowdate.getDate()-date.getDate()>0){
                    int connection=LooseLabellist.get(i).getConnection()+1;
                    LooseLabellist.get(i).setConnection(connection);
                    if(looseLabelMapper.updateByid( LooseLabellist.get(i))>0){
                        logger.info("今日已更新债权权重");
                    }else {
                        logger.info("债权权重更新失败");
                    }
                }
            }
        }



        //15天删除管理员
        try {
            List<Admin> adminlist=adminMapper.selectAll();
            for(int i=0;i<adminlist.size();i++){
                Date date = adminlist.get(i).getAdata();
                int aId = adminlist.get(i).getAId();
                if(nowdate.getMonth()==date.getMonth()){
                    if(nowdate.getDate()-date.getDate()>15){
                        if(adminMapper.deleteById(aId)>0){
                            logger.info("已清理门户");
                        }else{
                            logger.info("管理员删除失败");
                        }
                    }
                }
            }
        }catch (NullPointerException e){
            logger.info("没有管理员需要删除");
        }




        //5天自动流标
        for (int i=0;i<LooseLabellist.size();i++){
            Integer labelid = LooseLabellist.get(i).getLabelid();
            Date date = LooseLabellist.get(i).getDateofissue();//发布日期
            if(nowdate.getMonth()==date.getMonth()){
                if(nowdate.getDate()-date.getDate()>5){
                  //修改状态
                    if(looseLabelMapper.updateStaByid(labelid)>0){
                        logger.info("今日已更新流标状态");
                    }else {
                        throw  new IlltionExption("流标状态更新失败");
                    }
                  //退还公司的钱    //退还用户的钱
                    String projectnumber = LooseLabellist.get(i).getProjectnumber();//唯一合同号
                    List<Debt_info> debt_info=debt_infoMapper.selectBynumber(projectnumber);
                   for (int o1=0;o1<debt_info.size();o1++){
                       Integer borrowerid = debt_info.get(o1).getBorrowerid();//用户id
                       Double matchedmoney = debt_info.get(o1).getMatchedmoney();//匹配金额
                       if(borrowerid==0){//公司
                           //还钱
                           if(moneyCountMapper.updateadd(matchedmoney)>0){
                               logger.info("今日还公司钱成功");
                           }else {
                               throw  new IlltionExption("今日还公司钱失败");
                           }
                           //往系统日志添加字段
                           Double money=moneyCountMapper.selectmoney();
                           Account_log account_log = new Account_log();
                           account_log.setAuserid(0);
                           account_log.setAmainaccountid(1);
                           account_log.setAreceiveorpay("收款");
                           account_log.setAtransferserialno(projectnumber);
                           account_log.setAdate(new Date());
                           account_log.setAtype("流标");
                           account_log.setAamount(matchedmoney);
                           account_log.setAbeforetradingmoney(money-matchedmoney);
                           account_log.setAaftertradingmoney(money);
                           int o=account_logMapper.sysinsert(account_log);
                           if(o==0){
                               throw new IlltionExption("添加日志失败");
                           }
                       }else{//用户
                           if(accountMapper.updateByUserKey(borrowerid,matchedmoney)>0){
                               logger.info("今日还款用户成功");
                           }else{
                               throw  new IlltionExption("今日还款用户失败");
                           }
                           User user = userMapper.selectByPrimaryKey(borrowerid);
                           //生成验证码
                           String code= "合同号"+projectnumber;
                           HashMap<String,Object> param=new HashMap<>();
                           param.put("code",code);
                           //使用验证码
                           Map isSend=sendSms.send(user.getPhone(),"SMS_205464231",param);
                           if((Boolean) isSend.get("boolean")){
                               logger.info("验证码发送成功");
                           }else{
                               throw new PhoneExption("验证码发送失败");
                           }
                       }
                   }
                }
            }
        }



        //官标用户投资表收益是否完成 与 已赚取利息
        List<Product_account> product_accounts = product_accountMapper.selectAll();
        for(int i=0;i<product_accounts.size();i++){
            Date date = product_accounts.get(i).getPenddate();
            if(nowdate.getYear()==date.getYear()&&nowdate.getMonth()==date.getMonth()&&nowdate.getDate()==date.getDate()){
               //产品到期
                //1.改用户投资表状态，已赚取利息
                Integer pid = product_accounts.get(i).getPid();
                //连本带息
                Double pendinvesttotalmoney = product_accounts.get(i).getPendinvesttotalmoney();
                //本金
                Double pamount = product_accounts.get(i).getPamount();
                //获取总计利息
                double lixi=pendinvesttotalmoney-pamount;
                product_accounts.get(i).setPearnedinterest(lixi);
                product_accounts.get(i).setPearningsisfinished("1");
                if(product_accountMapper.updateByPrimaryKey(product_accounts.get(i))>0){
                    logger.info("用户投资表更新成功");
                }else {
                    logger.info("用户投资表更新失败");
                }

                //2.还钱给到用户的可用余额
                Integer puid = product_accounts.get(i).getPuid();
                Account account = accountMapper.selectByPrimaryKey(puid);
                //增加金额
                account.setBalance(account.getBalance()+pendinvesttotalmoney);
                //减少冻结金额
                account.setFrozen(account.getFrozen()-pendinvesttotalmoney);
                if(accountMapper.updateByPrimaryKey(account)>0){
                    logger.info("用户还钱成功给到公司");
                }else {
                    logger.info("用户还钱失败");
                }

                //3.公司扣钱
                if(moneyCountMapper.updateadd(pendinvesttotalmoney)>0){
                    logger.info("公司退钱成功");
                }else {
                    throw  new IlltionExption("公司退钱失败");
                }

                //4.生成记录表
                Double money=moneyCountMapper.selectmoney();
                Account_log account_log = new Account_log();
                account_log.setAuserid(puid);
                account_log.setAmainaccountid(1);
                account_log.setAreceiveorpay("付款");
                account_log.setAtransferserialno(product_accounts.get(i).getPserialno());
                account_log.setAdate(new Date());
                account_log.setAtype("官标日期已满");
                account_log.setAamount(pendinvesttotalmoney);
                account_log.setAbeforetradingmoney(money);
                account_log.setAaftertradingmoney(money-pendinvesttotalmoney);
                int o=account_logMapper.sysinsert(account_log);
                if(o==0){
                    throw new IlltionExption("添加日志失败");
                }

            }else{
                //满了多少个月
                int month=0;
                if(nowdate.getDate()==date.getDate()){
                    if(nowdate.getMonth()==date.getMonth()){
                        month=(nowdate.getYear()-date.getYear())*12;
                    }else{
                        if(nowdate.getYear()==date.getYear()){
                            month=nowdate.getMonth()-date.getMonth();
                        }else{
                            month=nowdate.getMonth()-date.getMonth();
                            month+=(nowdate.getYear()-date.getYear())*12;
                        }
                    }
                }else{
                    if(nowdate.getMonth()==date.getMonth()){
                        month=(nowdate.getYear()-date.getYear())*12-1;
                    }else{
                        if(nowdate.getYear()==date.getYear()){
                            month=nowdate.getMonth()-date.getMonth()-1;
                        }else{
                            month=nowdate.getMonth()-date.getMonth();
                            month+=(nowdate.getYear()-date.getYear())*12-1;
                        }
                    }
                }

                //1.更改用户投资表 已经转取的利息
                Integer pid = product_accounts.get(i).getPid();
                //每月赢取的利息
                Double pmonthinterest = product_accounts.get(i).getPmonthinterest();
                //设置利息
                product_accounts.get(i).setPearnedinterest(pmonthinterest*(-1)*month);
                if(product_accountMapper.updateByPrimaryKey(product_accounts.get(i))>0){
                    logger.info("用户投资记录表更新成功");
                }else {
                    logger.info("用户投资记录表更新失败");
                }

                //2.增加冻结资金余额
                Integer puid = product_accounts.get(i).getPuid();
                Account account = accountMapper.selectByPrimaryKey(puid);
                account.setFrozen(account.getFrozen()+pmonthinterest*month);
                if(accountMapper.updateByPrimaryKey(account)>0){
                    logger.info("用户还钱成功给到个人");
                }else {
                    logger.info("用户还钱失败");
                }
            }
        }



        //散标匹配金额 自动打款
        List<LooseLabel>  looseLabels =  looseLabelMapper.selectall();
        System.out.println(looseLabels);
        for (int i = 0; i <looseLabels.size() ; i++) {
            System.out.println(looseLabels.get(i).getStatus());
            if (looseLabels.get(i).getStatus()==4){
                System.out.println(looseLabels.get(i).getDebtormoney());
                System.out.println(looseLabels.get(i).getTransferredamount());
                if (looseLabels.get(i).getDebtormoney()-looseLabels.get(i).getTransferredamount()==0){
                    System.out.println(222);
                    Calendar rightNow = Calendar.getInstance();
                    rightNow.setTime(new Date());
                    rightNow.add(Calendar.MONTH, 1);
                    Date dt1 = rightNow.getTime();//还款日
                    //还款金额
                    double v = looseLabels.get(i).getTransferredamount() *(1+looseLabels.get(i).getIncomerate() * 30*looseLabels.get(i).getPeriods()) / looseLabels.get(i).getPeriods();
                    looselabel_record looselabel_records = new looselabel_record();
                    looselabel_records.setClaimsId(looseLabels.get(i).getLabelid());
                    looselabel_records.setUserId(looseLabels.get(i).getDeborid());
                    looselabel_records.setReceivableMoney(v);
                    looselabel_records.setReceivableDate(dt1);
                    looselabel_records.setCurrentTerm(1);
                    looselabel_records.setIsReturned(0);
                    looseLabelMapper.updateByids(5,looseLabels.get(i).getLabelid(),new Date());//修改散标状态和筹款放款时间
                    accountMapper.updateByUserKey(looseLabels.get(i).getDeborid(),looseLabels.get(i).getTransferredamount());//给用户放款
                    moneyCountMapper.update(looseLabels.get(i).getTransferredamount());//公司账户资金减少
                    List<Debt_info>  debtInfolist = debt_infoMapper.selectBynumber(looseLabels.get(i).getProjectnumber());
                    for (int j = 0; j <debtInfolist.size(); j++) {
                        debt_infoMapper.updateBykey(debtInfolist.get(j).getId(),"11404");//修改债权状态为生效计息中
                    }
                    Account_log account_log = new Account_log();
                    account_log.setAuserid(looseLabels.get(i).getLabelid());
                    account_log.setAmainaccountid(1);
                    account_log.setAreceiveorpay("付款");
                    account_log.setAtransferserialno(looseLabels.get(i).getProjectnumber());
                    account_log.setAdate(new Date());
                    account_log.setAtype("散标");
                    account_log.setAdescreption("散标筹码放款");
                    double money = moneyCountMapper.selectmoney();
                    account_log.setAamount(looseLabels.get(i).getTransferredamount());
                    account_log.setAbeforetradingmoney(money);
                    account_log.setAaftertradingmoney(money-looseLabels.get(i).getTransferredamount());
                    int o=account_logMapper.sysinsert(account_log);
                    Product_account product_account = product_accountMapper.selectBypProductName(looseLabels.get(i).getProjectnumber());
                    product_account.setPintereststartdate(new Date());
                    looselabel_recordMappers.insert(looselabel_records);
                    System.out.println(1111);
                }
            }
        }




        //个人中心每天的利息 0.015%
        List<User> users = userMapper.selectAll();
        System.out.println(users);
        for (User user : users) {
            Integer borrowerid = user.getId();
            Account account = accountMapper.selectByPrimaryKey(1);
            Double invest = account.getBalance();
            Double capitaltotal = account.getCapitaltotal();
            Double matchedmoney = invest * 0.00015;
            if(capitaltotal==null){
                capitaltotal=0+matchedmoney;
            }else {
                capitaltotal = capitaltotal + matchedmoney;
            }
            int i=accountMapper.updateByUserKey1(1, matchedmoney,capitaltotal);
            Double money = matchedmoney;
            int update = moneyCountMapper.update(money);
            if(i==0||update==0){
                throw new UpmysqlException("利息更新失败");
            }

        }





    }
}